import java.io.IOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.Random;

import Messages.MonitorDataTypeEnum;
import Messages.OSTypeEnum;


public class MThread implements Runnable {
	private volatile boolean shutdown=false;

	/* Private thread params */
	private String par;
	private DataChannel dataChannel;
	private MonitorDataTypeEnum monitorDataType;
	private Object[] parameters;
	private OSTypeEnum os;
	private Random rand_timer;
	
	/* Method for sending the shutdown signal */
    public void shutdown(){this.shutdown=true;}
    
    
    public MThread(String monitorIP, int monitorPort,
			MonitorDataTypeEnum monitorDataType, Object[] parameters) {
    	
    	/* Detect OS */
    	os = OsDetect.getOS();
    	
        /* Save params */
    	this.par = monitorIP + monitorDataType.name();
    	this.monitorDataType = monitorDataType;
    	this.parameters = parameters;
    	
    	/* Open data channel */
        try {
			dataChannel = new DataChannel(monitorIP, monitorPort);
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
        rand_timer = new Random();  
    }
    @Override
    public void run() {
    	
    	/* while shutdown signal havn't sent */
        while(this.shutdown==false){
            System.out.print("signaling"+this.par+"\n");
            String res="0";

            try {
				Thread.sleep(rand_timer.nextInt(500));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
            /* Get monitored value */
            switch(this.monitorDataType) {
    			case Cpu:
    				res = DataType.cpu(this.os);
    				break;
    			case Memory:
    				res = DataType.memory(this.os);
    				break;
    			case Disk:
    				res = DataType.disk(this.os);
    				break;
    			case Ping:
    				res = DataType.ping((String)this.parameters[0]);
    				break;
            }
            
            /* send package to monitor with data */
            try {        	
				dataChannel.SendData(monitorDataType, this.parameters, Calendar.getInstance().getTime(), res);
			} catch (IOException e) {
				e.printStackTrace();
			}
            
            try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
        }
        System.out.print("Shutting down thread");
    }
}
